/* 
 * 创建日期 2011-3-31
 *
 * 成都天和软件公司
 * 电话：028-85425861 
 * 传真：028-85425861-8008 
 * 邮编：610041 
 * 地址：成都市武侯区航空路6号丰德万瑞中心B座1001 
 * 版权所有
 */
package  org.fantasy.cpp.core.dao.jdbc.mapper;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.jdbc.core.RowMapper;

import  org.fantasy.common.util.StringUtil;

/**
 * 公共匹配器
 * 
 * @author 王文成
 * @version 1.0
 * @since 2011-3-31
 */
@SuppressWarnings("unchecked")
public class CommonMapper<T> implements RowMapper {

	private Class<T> type;
	
	public CommonMapper(Class<T> type) {
		this.type = type;
	}

	public T mapRow(ResultSet rs, int index) throws SQLException {
		List<String> fields = getFields(rs);
		Map<String,Object> row = new HashMap<String,Object>();
        for (String field : fields) {
            Object value = rs.getObject(field);
            String javaName = StringUtil.getFieldString(field);
            row.put(javaName, value);
        }
        try {
        	T bean = type.newInstance();
			BeanUtils.copyProperties(bean, row);
			return bean;
		} catch (Exception e) {
			throw new SQLException(e.getMessage(),e);
		}
	}
	
	/**
     * 取得列信息
     * 
     * @param rs
     * @return
     * @throws SQLException
     */
    private List<String> getFields(ResultSet rs) throws SQLException {
    	List<String> cols = new ArrayList<String>(16);
        ResultSetMetaData metaData = rs.getMetaData();
        int count = metaData.getColumnCount();
        for (int i = 1; i <= count; i++) {
            String colName = metaData.getColumnName(i);
            cols.add(colName);
        }
        return cols;
    }
}
